﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Configuration;

namespace CrmPluginAssemblyExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Count() == 0)
            {
                Console.WriteLine("You must provide a plug-in name.");
                return;
            }

            SqlParameter param = new SqlParameter("@PluginName", args[0]);

            var connectionString = ConfigurationManager.ConnectionStrings["CrmDatabseConnection"];

            if (connectionString == null)
            {
                Console.WriteLine("No connection string found.");
                return;
            }


            SqlConnection conn = new SqlConnection(connectionString.ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT name, content, * FROM PluginAssemblyBase WHERE name = @PluginName", conn);
            cmd.Parameters.Add(param);
            conn.Open();

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet dataset = new DataSet();
            adapter.Fill(dataset);

            if(dataset.Tables.Count == 0 || dataset.Tables[0].Rows.Count == 0)
            {
                Console.WriteLine("No plugin assembly found.");
                return;
            }

            foreach (DataRow row in dataset.Tables[0].Rows)
            {

                string content = (string)row["content"];
                byte[] filebytes = Convert.FromBase64String(content);
                FileStream fs = new FileStream((string)row["name"] + ".dll", FileMode.CreateNew, FileAccess.Write, FileShare.None);
                fs.Write(filebytes, 0, filebytes.Length);
                fs.Close();

                

            }



        }
    }
}
